package Doem;
//自己实现一个阻塞队列，并实现生产者消费者模型
public class MyBlockingQueue {
    private String[] data=null;
    private int head=0;//队首
    private int tail=0;//队尾
    private int size=0;//元素个数
    public MyBlockingQueue(int capacity){
        data=new String[capacity];
    }
    //入队列
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size>=data.length){
                this.wait();
            }
            data[tail]=elem;
            tail++;
            if(tail>= data.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }
    //出队列
    public String take() throws InterruptedException {
        synchronized (this){
            while(size==0){
                this.wait();
            }
            String ret=data[head];
            head++;
            if(head>= data.length){
                head=0;
            }
            size--;
            this.notify();
            return ret;
        }
    }

    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue(10);
        Thread producer=new Thread(()->{
            int n=0;
            while(true){
                try {
                    queue.put(n+" ");
                    System.out.println("生产元素"+n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread consumer=new Thread(()->{
            int n=0;
            while(true){
                try {
                    String ret=queue.take();
                    System.out.println("消费元素"+n);
                    n--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
        consumer.start();
    }
}
